package com.kyz.speechsdk;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.kyz.speechsdk.engine.IflyEngine;
import com.kyz.speechsdk.engine.LocalEngine;
import com.kyz.speechsdk.engine.abstracts.UnderstandResultCallback;
import com.kyz.speechsdk.engine.entity.EngineResult;
import com.kyz.speechsdk.ifly.interfaces.IRecognizeListener;
import com.kyz.speechsdk.ifly.interfaces.IResultProcessor;
import com.kyz.speechsdk.ifly.interfaces.ISpeakListener;


public class SpeechPlugin {
    private static final String TAG = "SpeechPlugin";
    private static final String VER = "1.0.0";

    private static SpeechPlugin mInstance;
    private Context mContext;
    private LocalEngine localEngine;
    private IflyEngine iflyEngine;

    private boolean canSpeakInterrupt = true;
    private boolean openAiuiRecognize = true;

    private IResultProcessor resultProcessor;

    private SpeechPlugin(Context context) {
        this.mContext = context;
        initDefaultEngineChain("586b9487", Environment.getExternalStorageDirectory().getAbsolutePath() + "/robot/命令集.xls");
    }

    public static SpeechPlugin createInstance(Context context) {
        if (mInstance == null) {
            mInstance = new SpeechPlugin(context.getApplicationContext());
        }
        return mInstance;
    }


    public static SpeechPlugin getInstance() {
        if (mInstance == null) {
            Log.e(TAG, "please call SpeechPlugin.createInstance first");
        }
        return mInstance;
    }

    public static String getVersion() {
        return VER;
    }

    /**
     * 初始化引擎
     *
     * @param iflyID          讯飞ID
     * @param localEnginePath 本地引擎配置路径
     */
    public void initDefaultEngineChain(String iflyID, String localEnginePath) {
        iflyEngine = new IflyEngine.Builder(mContext.getApplicationContext())
                .setIflyAppID(iflyID)
                .build();
        localEngine = new LocalEngine.Builder()
                .setConfigFilePath(localEnginePath)
                .setNextEngine(iflyEngine)
                .build();
        localEngine.setUnderstandResultCallback(new UnderstandResultCallback() {
            @Override
            public void onResult(EngineResult result) {
                if (null != resultProcessor) {
                    resultProcessor.onEngineResult(result);
                }
            }
        });
        iflyEngine.setRecognizeTextCallback(new IflyEngine.RecognizeTextCallback() {
            @Override
            public void onRecognizeText(String text) {
                if (openAiuiRecognize) {
                    localEngine.onTextUnderstand(text);
                }
            }
        });
    }

    /**
     * 设置允许打断语音合成
     *
     * @param canSpeakInterrupt
     */
    public void setCanSpeakInterrupt(boolean canSpeakInterrupt) {
        this.canSpeakInterrupt = canSpeakInterrupt;
    }

    public boolean isCanSpeakInterrupt() {
        return canSpeakInterrupt;
    }

    /**
     * @param openAiuiRecognize 是否允许自动语义理解
     */
    public void setOpenAiuiRecognize(boolean openAiuiRecognize) {
        this.openAiuiRecognize = openAiuiRecognize;
    }

    public boolean isOpenAiuiRecognize() {
        return openAiuiRecognize;
    }

    /**
     * 语音识别进度回调
     */
    public void setRecognizeListener(IRecognizeListener mRecognizerListener) {
        if (iflyEngine != null) {
            iflyEngine.setRecognizeListener(mRecognizerListener);
        }
    }

    /**
     * 打开录音开始识别
     */
    public void startRecognize() {
        if (iflyEngine != null) {
            iflyEngine.startRecognize();
        }
    }

    /**
     * 停止录音
     */
    public void stopRecognize() {
        if (iflyEngine != null) {
            iflyEngine.stopRecognize();
        }
    }

    public boolean isRecognizing() {
        return iflyEngine != null && iflyEngine.isRecognizing();
    }

    /**
     * 设置语音识别参数
     *
     * @param language      语言
     * @param bos           前端点检测，取值范围[0,10000ms]
     * @param eos           后端点检测，取值范围[0,10000ms]
     * @param speechtimeout 语音输入超时时间
     * @param nettimeout    网络连接超时时间 设置等待结果最长的时间
     * @param pcmpath       识别音频保存路径
     */
    public void setRecognizeParams(String language, int bos, int eos, int speechtimeout, int nettimeout, String pcmpath) {
        if (iflyEngine != null) {
            iflyEngine.setRecogParams(language, bos, eos, speechtimeout, nettimeout, pcmpath);
        }
    }

    /**
     * 语义理解
     */
    public void onTextUnderstand(String text) {
        if (localEngine != null) {
            localEngine.onTextUnderstand(text);
        }
    }

    /**
     * 仅使用Ifly语义理解
     */
    public void onSingleIflyUnderstand(String text) {
        if (iflyEngine != null) {
            iflyEngine.onSingleEngineTextUnderstand(text);
        }
    }

    /**
     * 仅使用Ifly语义理解
     */
    public void onSingleLocalUnderstand(String text) {
        if (localEngine != null) {
            localEngine.onSingleEngineTextUnderstand(text);
        }
    }

    /**
     * 文本语音合成
     */
    public void startSpeak(String text) {
        this.startSpeak(text, null);
    }


    public void startSpeak(String text, ISpeakListener listener) {
        if (this.canSpeakInterrupt) {
            if (!TextUtils.isEmpty(text)) {
                if (iflyEngine != null) {
                    iflyEngine.setSpeakListener(listener);
                    iflyEngine.startIflySpeak(text);
                }
            }
        }
    }


    public void stopSpeak() {
        if (iflyEngine != null) {
            iflyEngine.stopSpeak();
        }
    }

    public void pauseSpeak() {
        if (iflyEngine != null) {
            iflyEngine.pauseSpeak();
        }
    }

    public void resumeSpeak() {
        if (iflyEngine != null) {
            iflyEngine.resumeSpeak();
        }
    }

    public boolean isSpeaking() {
        return iflyEngine != null && iflyEngine.isSpeaking();
    }

    /**
     * 设置语音合成参数
     *
     * @param voicerName 发音人
     * @param speed      语速
     * @param pitch      语调
     * @param volume     音量
     */
    public void setSpeakParams(String voicerName, int speed, int pitch, int volume) {
        if (iflyEngine != null) {
            iflyEngine.setSpeakParams(voicerName, speed, pitch, volume);
        }
    }

    /**
     * 设置全局文本合成监听
     */
    public void setGlobalSpeakListener(ISpeakListener l) {
        if (iflyEngine != null) {
            iflyEngine.setGlobalSpeakListener(l);
        }
    }

    /**
     * 语义理解结果回调
     */
    public void setEngineResultProcessor(IResultProcessor resultProcessor) {
        this.resultProcessor = resultProcessor;
    }


    public void destroy() {
        if (iflyEngine != null) {
            iflyEngine.destoryEngine();
            iflyEngine = null;
        }
        if (localEngine != null) {
            localEngine.destoryEngine();
            localEngine = null;
        }
    }
}
